<template>
  <el-drawer v-model="drawerVisible" :z-index="1000" :destroy-on-close="true" size="560px" :title="`${drawerProps.title}`">
    <el-form
      ref="examQuestionFormRef"
      label-width="120px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-form-item label="题干名称" prop="questionStem">
        <el-input v-model="drawerProps.row!.questionStem" placeholder="请填写题干名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="题型" prop="questionType">
        <el-select v-model="drawerProps.row!.questionType" @change="_selQuestionType">
          <el-option :label="item.label" :value="item.value" v-for="item in questionType" :key="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="答案" prop="questionAnswer" v-if="drawerProps.row!.questionType">
        <el-input
          type="textarea"
          v-model="drawerProps.row!.questionAnswer"
          placeholder="请填写答案"
          clearable
          v-if="drawerProps.row!.questionType > 3"
        ></el-input>
        <el-select v-model="drawerProps.row!.questionAnswer" v-if="drawerProps.row!.questionType === 3">
          <el-option label="正确" value="T" />
          <el-option label="错误" value="F" />
        </el-select>
        <el-select
          v-model="drawerProps.row!.questionAnswer"
          v-if="drawerProps.row!.questionType <= 2"
          :multiple="drawerProps.row!.questionType === 2"
        >
          <el-option :label="val" :value="val" v-for="val in optionCodeList" :key="val" />
        </el-select>
      </el-form-item>
      <el-form-item label="分值" prop="questionScore">
        <el-input v-model="drawerProps.row!.questionScore" placeholder="请填写分值" clearable></el-input>
      </el-form-item>
    </el-form>
    <div class="optionList" v-if="drawerProps.row!.questionType && drawerProps.row!.questionType <= 2 && optionList.length">
      <div class="optionTitle">选择题选项</div>
      <div class="optionItem" v-for="(item, index) in optionList" :key="item.optionCode">
        <span class="optionNo">{{ index + 1 }}.</span>
        <el-select class="optionCode" v-model="item.optionCode">
          <el-option :label="val" :value="val" v-for="val in optionCodeList" :key="val" />
        </el-select>
        <el-input class="optionContent" placeholder="请填写选项内容" v-model="item.optionContent" />
        <span class="delBtn">
          <el-icon color="var(--el-color-primary)" @click="_delOption(index)" v-if="optionList.length > 1"><Delete /></el-icon>
        </span>
      </div>
      <div class="addOptionBtn">
        <el-button type="primary" plain @click="_addOption">添加选项</el-button>
      </div>
    </div>
    <template #footer>
      <el-button @click="_colse">取消</el-button>
      <el-button type="primary" v-show="!drawerProps.isView" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="ExamQuestionDrawer">
import { ref, reactive } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { questionType } from "@/utils/serviceDict";
import { ExamQuestion, ResultData } from "@/api/interface";
import { Delete } from "@element-plus/icons-vue";

import { getExamQuestionDtl } from "@/api/modules/examManage/examQuestion";
const optionCodeList = [...Array(26)].map((v, i) => String.fromCharCode(i + 65));
const optionList: any = ref([]);
const validateNumber = (rule: any, value: string, callback: (arg0?: Error | undefined) => void) => {
  if (!/^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/.test(value)) {
    callback(new Error("请输入数字值"));
  } else {
    callback();
  }
};
const rules = reactive({
  questionStem: [{ required: true, message: "请填写题干" }],
  questionType: [{ required: true, message: "请选择题型" }],
  questionAnswer: [{ required: true, message: "请填写答案" }],
  questionScore: [
    { required: true, message: "请填写分值" },
    { validator: validateNumber, message: "分值必须由数字组成" }
  ]
});

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<ExamQuestion.ResExamQuestionList>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
  resetTableList?: () => void;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {}
});
// 接收父组件传过来的参数
const acceptParams = async (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
  optionList.value = [];
  if (drawerProps.value.title !== "新增") {
    if (drawerProps.value.row!.questionType === 2) {
      drawerProps.value.row!.questionAnswer = (drawerProps.value.row!.questionAnswer as string).split("");
    }

    try {
      const { result } = (await getExamQuestionDtl({ questionId: drawerProps.value.row!.questionId as number })) as ResultData;
      optionList.value = result.optionList ?? [];
    } catch (error) {}
  }
};

// 提交数据（新增/编辑）
const examQuestionFormRef = ref<FormInstance>();

/**
 * 选择题型
 */
const _selQuestionType = (value: any) => {
  drawerProps.value.row!.questionAnswer = value === 2 ? [] : "";
  // optionList.value = [];
  if (value <= 2) {
    !optionList.value.length && optionList.value.push({ optionCode: "", optionContent: "" });
  }
};
/**
 * 新增选择题选项
 */
const _addOption = () => {
  optionList.value.push({ optionCode: "", optionContent: "" });
};
/**
 * 删除选择题选项
 */
const _delOption = (index: number) => {
  if (optionList.value.length <= 1) return;
  optionList.value.splice(index, 1);
};
/**
 * 关闭弹窗
 */
const _colse = () => {
  drawerVisible.value = false;
  examQuestionFormRef.value && examQuestionFormRef.value.resetFields();
};
/**
 * 提交信息
 */
const handleSubmit = () => {
  examQuestionFormRef.value!.validate(async valid => {
    if (!valid) return;
    console.log(drawerProps.value.row!.questionAnswer);
    let isReturn: boolean = false;
    let questionAnswer = drawerProps.value.row.questionAnswer;

    if ((drawerProps.value.row.questionType as number) <= 2) {
      optionList.value.forEach((item: any) => {
        if (isReturn) return false;
        if (!item.optionCode || !item.optionContent) {
          isReturn = true;
        }
      });
    }

    if (isReturn) {
      ElMessage.error("请检查选项列表,选项列表子项值不能为空");
      return false;
    }

    if (drawerProps.value.row!.questionType === 1) {
      if (!optionList.value.map((item: any) => item.optionCode).includes(questionAnswer)) {
        ElMessage.error("试题选项不包含题目答案选项");
        return false;
      }
    }

    if (drawerProps.value.row!.questionType === 2) {
      if (!questionAnswer.every((val: any) => optionList.value.map((item: any) => item.optionCode).includes(val))) {
        ElMessage.error("试题选项不包含题目答案选项");
        return false;
      }
      questionAnswer = (JSON.parse(JSON.stringify(drawerProps.value.row))!.questionAnswer as string[]).join("");
    }

    try {
      await drawerProps.value.api!({
        ...drawerProps.value.row,
        optionList: (drawerProps.value.row!.questionType as number) <= 2 ? optionList.value : [],
        questionAnswer
      });
      ElMessage.success({ message: `${drawerProps.value.title}成功！` });
      drawerProps.value.title === "新增" ? drawerProps.value.resetTableList!() : drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};
defineExpose({
  acceptParams
});
</script>

<style lang="scss" scoped>
.optionItem {
  display: flex;
  align-items: center;

  // justify-content: space-between;
  padding: 10px 0 10px 20px;
  .optionNo {
    margin-right: 10px;
    font-size: 14px;
    color: #666666;
  }
  .optionCode,
  .optionContent {
    width: 220px;
    margin-right: 10px;
  }
}
.optionTitle {
  padding: 10px 20px;
  font-size: 14px;
  color: #666666;
}
.addOptionBtn {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px 0;
}
.delBtn {
  cursor: pointer;
}
</style>
